import {createRouter, createWebHashHistory} from 'vue-router';
import {ElMessage} from "element-plus";
import {service} from '@/utils/service';
import store from '@/vuex/index';

const Login = () => import('@/views/AppLogin');
const Register = () => import('@/views/AppRegister');
const NotFound = () => import('@/views/NotFound');

const routes = [
    {
        path: '/',
        redirect: '/login'
    },
    {
        path: '/login',
        name: 'Login',
        component: Login,
        meta: {requireLogin: false}
    },
    {
        path: '/register',
        name: 'Register',
        component: Register,
        meta: {requireLogin: false}
    },
    {
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: NotFound,
        meta: {requireLogin: false}
    }
];
const router = createRouter({
    strict: true,
    sensitive: true,
    routes,
    history: createWebHashHistory()
});

(function () {
    //前置路由守卫
    router.beforeEach(async (to) => {
        if (to.meta.requireLogin && !service.isLogin()) {
            ElMessage({
                showClose: false,
                message: '请登录',
                type: 'error',
            });
            return {
                path: '/login',
                query: {redirect: to.fullPath}
            }
        }
        if (service.isLogin()) {
            if (!store.getters.checkAddRoute) {
                await service.addRoute(router);
                store.dispatch('handleChangeIsAddRouter', true);
                await router.replace(to.fullPath);
            } else {
                return true;
            }
        } else {
            return true;
        }
    });

    router.onError((err) => {
        console.log(err);
    })
}());
export default router;